package com.kyzh.core.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.*
import android.content.Context.VIBRATOR_SERVICE
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.provider.MediaStore
import android.util.Base64
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.jiguang.verifysdk.api.JVerifyUIConfig
import com.bytedance.hume.readapk.HumeSDK
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.entity.node.BaseNode
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.WriterException
import com.google.zxing.qrcode.QRCodeWriter
import com.gushenge.atools.util.ADate
import com.gushenge.core.beans.*
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.dao.MMKVConsts.uid
import com.gushenge.core.requests.AppRequest
import com.gushenge.core.toast
import com.hjq.language.MultiLanguages
import com.kyzh.core.MyApplication
import com.kyzh.core.R
import com.kyzh.core.pager.gamedetail.GameDetailActivity1
import com.kyzh.core.pager.login.LoginActivity
import com.kyzh.core.adapters.ReViewImageAdapter
import com.kyzh.core.pager.gamedetail.GMGameDetailActivity1
import com.kyzh.core.utils.walle.WalleChannelReader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.umeng.socialize.ShareAction
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.umeng.socialize.shareboard.ShareBoardConfig
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.indicator.enums.IndicatorSlideMode
import org.jetbrains.anko.*
import org.litepal.LitePal
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

//判断是否显示分享  true 显示  false 不显示
fun Context.showShare(): Boolean {
    if (packageName == "a94hwan.bjkyzh.star") {
        return true
    } else if (MyApplication.qqzone == "101559064" || MyApplication.weixin == "wx928808eb5354008a") {

        return false
    }
    return true
}

/*ListPopupwindow*/
private var dialog: AlertDialog? = null
fun Activity.shouListWindow(
    arrayList: ArrayList<BaseNode>,
    listener: Int.() -> Unit,
) {
    dialog = AlertDialog.Builder(this, R.style.kyzhGuestLoginDialog)
        .setView(getView(arrayList, listener))
        .setCancelable(false).create()
    dialog?.show()

}

private fun Activity.getView(
    arrayList: ArrayList<BaseNode>,
    listener: Int.() -> Unit,
): View {
    val view = View.inflate(this, R.layout.recyclerview, null)


    val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
    val root = view.findViewById<SmartRefreshLayout>(R.id.root)
    root.setEnableRefresh(false)
    root.setEnableLoadMore(false)
    recyclerView.layoutManager = LinearLayoutManager(this)

    val adapter = Adapter(android.R.layout.simple_list_item_1, arrayList)
    recyclerView.adapter = adapter

    adapter.setOnItemClickListener { adapter, view, position ->
        listener(position)
        dialog?.dismiss()
    }
    return view
}

private class Adapter(layout: Int, beans: ArrayList<BaseNode>) :
    BaseQuickAdapter<BaseNode, BaseViewHolder>(layout, beans) {

    override fun convert(helper: BaseViewHolder, item: BaseNode) {
        (item as Small.Data).apply {
            helper.setText(
                android.R.id.text1,
                "${gname}(${role_name})${this.level}${context.getString(R.string.level)}"
            )
                .setTextColor(
                    android.R.id.text1,
                    context.resources.getColor(R.color.font_33)
                )
            helper.getView<TextView>(android.R.id.text1).setTypeface(Typeface.DEFAULT_BOLD)
            val text = helper.getView<TextView>(android.R.id.text1)
            text.gravity = Gravity.CENTER
        }
    }
}

/*打开游戏详情页*/
public fun Context.startGameDetailActivity(gid: String?) {
    startGameDetailActivity1(this, gid)
}



public fun Fragment.startGameDetailActivity(gid: String?) {
    startGameDetailActivity1(requireActivity(), gid)
}
public fun Fragment.startGameDetailActivity2(gid: String?) {
    startGameDetailActivity2(requireActivity(), gid)
}


public fun Activity.startGameDetailActivity(gid: String?) {
    startGameDetailActivity1(this, gid)
}

private fun startGameDetailActivity1(context: Context, gid: String?) {
    gid?.let {
        MMKVConsts.gid = gid
        GameDetailActivity1.start(context, gid)
//        context.startActivity<GameDetailActivity>()
    }
    gid ?: context.toast(context.getString(R.string.openGameFailed))
}

private fun startGameDetailActivity2(context: Context, gid: String?) {
    gid?.let {
        MMKVConsts.gid = gid
        GMGameDetailActivity1.start(context, gid, type = "gm")
    }
    gid ?: context.toast(context.getString(R.string.openGameFailed))
}

/*震动*/
public fun Context.vibrate(time: Long) {
    vibrated(this, time)
}

public fun Fragment.vibrate(time: Long) {
    vibrated(requireActivity(), time)
}

public fun Activity.vibrate(time: Long) {
    vibrated(this, time)
}

private fun vibrated(context: Context, time: Long) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(time)
    } else {
        (context.getSystemService(VIBRATOR_SERVICE) as Vibrator).vibrate(
            VibrationEffect.createOneShot(
                time,
                VibrationEffect.DEFAULT_AMPLITUDE
            )
        )
    }
}

/*AES加密*/

// 加密
@Throws(Exception::class)
fun aesEcb(sSrc: String): String {
    val sKey = "mtetbpryjhdxmnhx"
    val raw = sKey.toByteArray(charset("utf-8"))
    val skeySpec = SecretKeySpec(raw, "AES")
    val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")//"算法/模式/补码方式"
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec)
    val encrypted = cipher.doFinal(sSrc.toByteArray(charset("utf-8")))
    val aesCrypt = Base64.encodeToString(encrypted, Base64.DEFAULT)//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    return aesCrypt.replace("+", "_")
}

/*MD5加密*/
fun md5(string: String): String {
    try {
        //获取md5加密对象
        val instance: MessageDigest = MessageDigest.getInstance("MD5")
        //对字符串加密，返回字节数组
        val digest: ByteArray = instance.digest(string.toByteArray())
        val sb: StringBuffer = StringBuffer()
        for (b in digest) {
            //获取低八位有效值
            val i: Int = b.toInt() and 0xff
            //将整数转化为16进制
            var hexString = Integer.toHexString(i)
            if (hexString.length < 2) {
                //如果是一位的话，补0
                hexString = "0" + hexString
            }
            sb.append(hexString)
        }
        return sb.toString()

    } catch (e: NoSuchAlgorithmException) {
        e.printStackTrace()
    }

    return ""
}

fun Context.appInstall(path: String, url: String) {
    installApk(MyApplication.instance, path)
    this.packageManager.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES)?.let {
        var list: DownTaskBean = LitePal.where("url = ?", url).findFirst(DownTaskBean::class.java)
        list.packageName = it.applicationInfo.packageName
        list.url = url
        list.save()
    }
}


fun Context.appInstall(task: com.liulishuo.okdownload.DownloadTask) {
    installApk(MyApplication.instance, task.file!!.absolutePath)
    this.packageManager.getPackageArchiveInfo(task.file!!.absolutePath, PackageManager.GET_ACTIVITIES)?.let {
        var list: DownTaskBean = LitePal.where("url = ?", task.url).findFirst(DownTaskBean::class.java)
        list.packageName = it.applicationInfo.packageName
        list.url = task.url
        list.save()
    }
}

fun installApk(context: Context, downloadApk: String) {
    val intent = Intent(Intent.ACTION_VIEW)
    val file = File(downloadApk)
//    L.i("安装路径==$downloadApk")
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        val apkUri: Uri = FileProvider.getUriForFile(
            context,
            context.packageName.toString() + ".fileprovider",
            file
        )
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
    } else {
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        val uri = Uri.fromFile(file)
        intent.setDataAndType(uri, "application/vnd.android.package-archive")
    }
    context.startActivity(intent)
}

/**
 * appliction MetaData读取
 */
fun Context.getChannel(name: String) {
    val channel = HumeSDK.getChannel(this)
    val channel1 = WalleChannelReader.getChannel(this)
    if (!channel.isNullOrEmpty()) {
        MMKVConsts.sub = channel
        Log.e("TAG", "使用巨量的getChannel: $channel ")
        return
    }
    if (!channel1.isNullOrEmpty()) {
        MMKVConsts.sub = channel1
        Log.e("TAG", "使用我们的 getChannel: 1$channel1")
        return
    }

    val sourceDir = applicationInfo.sourceDir
    var zipfile: ZipFile? = null
    val flag = "META-INF/${name}_"
    try {
        zipfile = ZipFile(sourceDir)
        val entries = zipfile.entries()
        while (entries.hasMoreElements()) {
            val entry = entries.nextElement() as ZipEntry
            val entryName = entry.name
            if (entryName.contains(flag)) {
                MMKVConsts.sub = entryName.replace(flag.toRegex(), "")
            }
        }
    } catch (e: IOException) {
        e.printStackTrace()
    } finally {
        try {
            zipfile?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    if ("coid" == name) {
        if (MMKVConsts.sub == "0") {
            getCoid()
        }
    } else {
        MMKVConsts.sub = "0"
    }

}

//获取id
private fun Context.getCoid() {
    val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    if (clipboardManager.primaryClipDescription?.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) == true) {
        val clipdata = clipboardManager.primaryClip
        val size = clipdata?.itemCount ?: 1
        val texts = arrayListOf<String>()
        for (i in 0 until size) {
            clipdata?.getItemAt(i)?.let {
                if (it.text.contains("coid_")) {
                    texts.add(it.text.toString())
                }
            }
        }
        if (texts.isNotEmpty()) {
            MMKVConsts.sub = texts[0].split("_")[1]
        } else {
            AppRequest.getMemberId()
        }
    } else {
        AppRequest.getMemberId()
    }
}
/*未分包检查登录*/

fun checkLogin(): Boolean {
    return uid != ""
}

fun Bitmap.getImageUri(inContext: Context): Uri {
    val bytes = ByteArrayOutputStream()
    this.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
    val path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), this, "Title", null)
    return Uri.parse(path)
}

/*分包检查登录*/
fun isLogin(): Boolean {
    return if (MMKVConsts.sub == "0") {
        true
    } else {
        uid.isNotEmpty()
    }
}

fun Fragment.startLogin(): Boolean {
    return requireActivity().startLogin()
}

fun Context.startLogin(): Boolean {
    return if (uid.isNotEmpty()) {
        true
    } else {
        startActivity<LoginActivity>()
        false
    }
}

/*检查是否是手机号*/


fun isPhone(phone: String): Boolean {

    return if (phone.isEmpty()) false else phone.length == 11
}


/*drawable 转 Uri*/
fun Context.drawableToUri(drawable: Int): Uri {
    return drawableToUri2(this, drawable)
}

fun Fragment.drawableToUri(drawable: Int): Uri {
    return drawableToUri2(requireContext(), drawable)
}

fun Activity.drawableToUri(drawable: Int): Uri {
    return drawableToUri2(this, drawable)
}


private fun drawableToUri2(context: Context, drawable: Int): Uri {
    val r = context.resources
    return Uri.parse(
        ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + r.getResourcePackageName(drawable) + "/"
                + r.getResourceTypeName(drawable) + "/"
                + r.getResourceEntryName(drawable)
    )
}

/*预览图片*/
fun Activity.reviewImages(images: ArrayList<String>, position: Int) {
    reviewImage(this, images, position)
}

fun Fragment.reviewImages(images: ArrayList<String>, position: Int) {
    reviewImage(requireContext(), images, position)
}

fun Context.reviewImages(images: ArrayList<String>, position: Int) {
    reviewImage(this, images, position)
}


private fun reviewImage(context: Context, images: ArrayList<String>, position: Int) {
    val dialog = Dialog(context, R.style.fullscreenDialog)
    val layoutInflater = context.layoutInflater
    val banner = layoutInflater.inflate(R.layout.banner_dialog, null) as BannerViewPager<Banner>
    val banners = arrayListOf<Banner>()
    for (i in images) {
        banners.add(Banner().also {
            it.image = i
        })
    }
    banner.setRevealWidth(0)
        .setIndicatorSlideMode(IndicatorSlideMode.SCALE)
        .setInterval(5000)
        .setAdapter(ReViewImageAdapter())
        .setOnPageClickListener { a, position ->
            dialog.dismiss()
        }
        .create(banners)
    banner.removeDefaultPageTransformer()
    banner.currentItem = position
    dialog.setCancelable(true)
    dialog.setContentView(banner)

    val window = dialog.window
    val decorView = window?.decorView
    val lp = window?.attributes
    lp?.width = WindowManager.LayoutParams.MATCH_PARENT
    lp?.height = WindowManager.LayoutParams.MATCH_PARENT
    dialog.window?.attributes = lp
    dialog.create()
    dialog.show()
}

fun Activity.reviewImagesFromUri(images: ArrayList<Uri>, position: Int) {
    reviewImageFromUri(this, images, position)
}

fun Fragment.reviewImagesFromUri(images: ArrayList<Uri>, position: Int) {
    reviewImageFromUri(requireContext(), images, position)
}

fun Context.reviewImagesFromUri(images: ArrayList<Uri>, position: Int) {
    reviewImageFromUri(this, images, position)
}


private fun reviewImageFromUri(context: Context, images: ArrayList<Uri>, position: Int) {
    val dialog = Dialog(context, R.style.fullscreenDialog)
    val layoutInflater = context.layoutInflater
    val banner = layoutInflater.inflate(R.layout.banner_dialog, null) as BannerViewPager<Banner>
    val banners = arrayListOf<Banner>()
    for (i in images) {
        banners.add(Banner().also {
            it.image = i.toString()
        })
    }
    banner.setRevealWidth(0)
        .setIndicatorSlideMode(IndicatorSlideMode.SCALE)
        .setInterval(5000)
        .setAdapter(ReViewImageAdapter())
        .setOnPageClickListener { a, position ->
            dialog.dismiss()
        }
        .create(banners)
    banner.removeDefaultPageTransformer()

    banner.currentItem = position
    dialog.setCancelable(true)
    dialog.setContentView(banner)
    dialog.create()
    val lp = dialog.window?.attributes
    lp?.width = WindowManager.LayoutParams.MATCH_PARENT
    lp?.height = WindowManager.LayoutParams.MATCH_PARENT
    dialog.window?.attributes = lp
    dialog.show()
}

/*bitmap转Base64*/
fun bitmapToBase64(bitmap: Bitmap): String {

    var result: String = ""
    var baos: ByteArrayOutputStream? = null
    try {
        baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos)

        baos.flush()
        baos.close()

        val bitmapBytes = baos.toByteArray()
        result = android.util.Base64.encodeToString(bitmapBytes, android.util.Base64.DEFAULT)
    } catch (e: IOException) {
        e.printStackTrace()
    } finally {
        try {
            if (baos != null) {
                baos.flush()
                baos.close()
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }

    }
    return result
}

public fun Context.loading(): AlertDialog {
    return loadingDialog(this)
}

public fun Fragment.loading(): AlertDialog {
    return loadingDialog(requireContext())
}

private fun loadingDialog(context: Context): AlertDialog {
    val dialog = AlertDialog.Builder(context, R.style.BDAlertDialog)
        .setView(
            context.UI {
                verticalLayout {
                    padding = dip(10)

                    progressBar {
                        progressDrawable = resources.getDrawable(R.drawable.loading_drawable)
                    }.lparams(dip(50), dip(50)) {
                        gravity = Gravity.CENTER_HORIZONTAL
                    }
                }
            }.view
        ).create()
    dialog.show()
    dialog.setCancelable(false)
    return dialog
}

fun Fragment.shareWeb(title: String, message: String, icon: String, url: String) {
    shareWebFun(requireActivity(), title, message, icon, url)
}

fun Activity.shareWeb(title: String, message: String, icon: String, url: String) {
    shareWebFun(this, title, message, icon, url)
}

private fun shareWebFun(context: Activity, title: String, message: String, icon: String, url: String) {
    val config = ShareBoardConfig()
    config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_CIRCULAR)
    config.setCancelButtonBackground(Color.rgb(240, 244, 246))
    config.setShareboardBackgroundColor(Color.rgb(240, 244, 246))
    config.setIndicatorVisibility(false)
    config.setTitleText(context.getString(R.string.share))
    val image = UMImage(context, icon)
    val web = UMWeb(url)
    web.title = title
    web.setThumb(image)
    web.description = message
    ShareAction(context)
        .withMedia(web)
        .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)
        .open(config)
}

var timeStamp = ""

val time: String
    get() {
        timeStamp = ADate.getStampAs13().toString()
        Log.e("time: ", timeStamp)
        return timeStamp
    }

/*接口验证*/
fun httpSign(vararg string: String): String {

    var result = ""
    for (key in string) {
        result += key
    }
    result += timeStamp
    result += "fsd213ewdsadqwe2121213edsad"
    Log.e("time: ", timeStamp)
    return md5(result)
}

fun Activity.oneKeyLoginConfig(): JVerifyUIConfig {
    return JVerifyUIConfig.Builder()
        .setStatusBarColorWithNav(true)
        .setNavColor(Color.WHITE)
        .setNavText(getString(R.string.onekeyLogin))
        .setStatusBarDarkMode(true)
        .setNavTextColor(Color.parseColor("#333333"))
        .setNavReturnImgPath("back")
        .setNavReturnBtnWidth(20)
        .setNavReturnBtnHeight(20)
        .setLogBtnImgPath("button_bg")
        .setPrivacyTextCenterGravity(true)
        .enableHintToast(true, Toast.makeText(this, "请先勾选协议", Toast.LENGTH_SHORT))
//            .setPrivacyState(true)
        .setAppPrivacyColor(Color.parseColor("#333333"), ContextCompat.getColor(this, R.color.colorPrimary))
        .setNumberColor(ContextCompat.getColor(this, R.color.colorPrimary))
        .build()
}

@SuppressLint("NewApi")
fun getToday(): String {
    val current = LocalDateTime.now()

    val formatter = DateTimeFormatter.BASIC_ISO_DATE
    return current.format(formatter)
}

fun View.onLoginClick(context: Context, listener: View.() -> Unit) {

    setOnClickListener {
        if (context.startLogin()) {
            it.listener()
        }
    }
}

fun EditText.enableEdit() {
    isFocusableInTouchMode = true
    isFocusable = true
    requestFocus()
}

fun EditText.disableEdit() {
    isFocusable = false;
    isFocusableInTouchMode = false
}

fun String.copy() {
    val manager = MyApplication.instance.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    manager.setPrimaryClip(ClipData.newPlainText(System.currentTimeMillis().toString(), this))
}

/*保存 图片*/
fun Activity.saveResource(image: Bitmap, name: String, listener: () -> Unit) {
    /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
        val values = ContentValues()
        values.put(MediaStore.Images.Media.DESCRIPTION, name)
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, name)
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
        values.put(MediaStore.Images.Media.TITLE, name)
        val resolver = MyApplication.instance.contentResolver
        val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        try {
            resolver.openOutputStream(uri!!).use { out ->
                if (!image.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                    throw IOException("Failed to compress")
                }
            }
            values.clear()
            values.put(MediaStore.MediaColumns.IS_PENDING, 0)
            values.putNull(MediaStore.MediaColumns.DATE_EXPIRES)
            resolver.update(uri, values, null, null)
            listener()
        }catch (e: Exception){
            e.printStackTrace()
            "保存失败，请手动截图前往".toast()
        }

    }else{*/
    MediaStore.Images.Media.insertImage(contentResolver, image, name, "")
    getString(R.string.pictureSaveSuccess).toast()
    listener()
    /*}*/
}

/**
 * 生成简单二维码
 *
 * @param content                字符串内容
 * @param width                  二维码宽度
 * @param height                 二维码高度
 * @param character_set          编码方式（一般使用UTF-8）
 * @param error_correction_level 容错率 L：7% M：15% Q：25% H：35%
 * @param margin                 空白边距（二维码与边框的空白区域）
 * @param color_black            黑色色块
 * @param color_white            白色色块
 * @return BitMap
 */
fun String.createQRCodeBitmap(
    width: Int = 200, height: Int = 200,
    character_set: String = "UTF-8", error_correction_level: String = "L",
    margin: String = "", color_black: Int = R.color.black, color_white: Int = R.color.white,
): Bitmap? {
    // 字符串内容判空
    this?.let {
        val hints: Hashtable<EncodeHintType, String> = Hashtable()
        // 字符转码格式设置
//        if (!TextUtils.isEmpty(character_set)) {
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//        }
        // 容错率设置
//        if (!TextUtils.isEmpty(error_correction_level)) {
//            hints.put(EncodeHintType.ERROR_CORRECTION, error_correction_level);
//        }
//        // 空白边距设置
//        if (!TextUtils.isEmpty(margin)) {
//            hints.put(EncodeHintType.MARGIN, margin);
//        }
        try {
            /** 2.将配置参数传入到QRCodeWriter的encode方法生成BitMatrix(位矩阵)对象 */
            val bitMatrix = QRCodeWriter().encode(this, BarcodeFormat.QR_CODE, width, height, hints)
            val pixels = IntArray(width * height)
            for (y in 0 until height) {
                for (x in 0 until width) {
                    //bitMatrix.get(x,y)方法返回true是黑色色块，false是白色色块
                    if (bitMatrix[x, y]) {
                        pixels[y * width + x] = color_black //黑色色块像素设置
                    } else {
                        pixels[y * width + x] = color_white // 白色色块像素设置
                    }
                }
            }
            /** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,并返回Bitmap对象 */
            /** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,并返回Bitmap对象  */
            val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
            return bitmap


        } catch (e: WriterException) {
            e.printStackTrace();

        }
    }
    return null
}

fun createQRImage(url: String?): Bitmap? {
    val QR_WIDTH = 300
    val QR_HEIGHT = 300
    try {
        //判断URL合法性
        if (url == null || "" == url || url.length < 1) {

            return null
        }
        val hints = Hashtable<EncodeHintType, String?>()
        hints[EncodeHintType.CHARACTER_SET] = "utf-8"
        //图像数据转换，使用了矩阵转换
        val bitMatrix = QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints)
        val pixels = IntArray(QR_WIDTH * QR_HEIGHT)
        //下面这里按照二维码的算法，逐个生成二维码的图片，
        //两个for循环是图片横列扫描的结果
        for (y in 0 until QR_HEIGHT) {
            for (x in 0 until QR_WIDTH) {
                if (bitMatrix[x, y]) {
                    pixels[y * QR_WIDTH + x] = -0x1000000
                } else {
                    pixels[y * QR_WIDTH + x] = -0x1
                }
            }
        }
        //生成二维码图片的格式，使用ARGB_8888
        val bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888)
        bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT)
        return bitmap
        //显示到一个ImageView上面
//        sweepIV.setImageBitmap(bitmap)
    } catch (e: WriterException) {
        e.printStackTrace()
    }
    return null
}

fun Activity.setLanguage(language: String) {
    MultiLanguages.setAppLanguage(
        this, when (language) {
            "0" -> Locale.SIMPLIFIED_CHINESE
            "1" -> Locale.ENGLISH
            "2" -> Locale.TRADITIONAL_CHINESE
            else -> Locale.SIMPLIFIED_CHINESE
        }
    )
}